<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/17
 * Time: 17:10
 */

namespace app\admin;

use think\cache\driver\Redis;
use think\Controller;
use think\Session;
use think\Config;
use app\admin\logic\Pub as PubLogic;

class Base extends Controller
{
    //后台登录者id
    public static $uid;

    public function _initialize()
    {
        //如果不存在session
        if (!Session::has(Config::get('rbac.user_auth_key'))) {
            $this->notLogin();
        }

        self::$uid = $this->getCurrentOperatorId();
        $action = $this->request->module() . "/" . $this->request->controller() . "/" . $this->request->action();
        if (\Rbac::checkAuth($action)) {
            return true;
        } else {
            if (!Session::has(Config::get('rbac.user_auth_key'))) {
                // throw new CHttpException(404); 主站上面需要跳转至404 本地及测试为了方便跳回登录页
                $this->redirect('Pub/login');
            } else {
                $this->redirect('Pub/noAuth');
            }
        }
    }
    /**
     * @todo 返回当前用户ID
     * @return type
     */
    protected function getCurrentOperatorId(){
        return Session::get(Config::get('rbac.user_auth_key'));
    }

    /**
     * @todo 未登录处理
     */
    protected function notLogin()
    {
        PubLogic::notLogin();
    }

    /**
     * @todo 删除角色同时清空跟角色关联的管理员在redis中的权限，重新赋值
     * @param $operatorids array 管理员id数组集合
    */
    public function delRoleAndRedis($operatorids)
    {
        $redis = new Redis();
        foreach($operatorids as $v){
            $name = $v. Config::get('rbac.redis_suffix');
            //只用重新赋值redis中存在的管理员
            if($redis->getHandler()->exists($name)){
                //先清空
                $redis->rm($name);
                $menus = \Rbac::getAuthMenu($v);
                //再存储
                $redis->set($name, $menus);
            }
        }
    }

}